package com.aabbc.v3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Game
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-05-28 10:00
 * @blame Team
 */
public class Game {

    private int startNum;
    private int endNum;
    private Rule[] orRules;
    private Rule[] andRules;

    public static Game getInstance(){
        return new Game();
    }

    public Game setStartNum(int num){
        startNum = num;
        return this;
    }

    public Game setEndNum(int num){
        endNum = num;
        return this;
    }

    public Game setOrRules(Rule... rules){
        orRules = rules;
        return this;
    }

    public Game setAndRules(Rule... rules){
        andRules = rules;
        return this;
    }

    public List<String> play(){
        if(startNum > endNum){
            throw new RuntimeException("startNum more than endNum");
        }
        List<String> results = new ArrayList<>();
        IntStream.range(startNum, endNum + 1).forEach(i -> {
            StringBuilder sb = new StringBuilder();
            if(orRules != null && orRules.length > 0){
                for(Rule rule : orRules){
                    String out = rule.say(i);
                    if(out != null){
                        sb.append(out);
                        break;
                    }
                }
            }
            if(sb.length() == 0 && andRules != null && andRules.length > 0){
                Stream.of(andRules).filter(rule -> rule.say(i) != null).forEach(rule -> sb.append(rule.say(i)));
            }
            if(sb.length() == 0){
                sb.append(i);
            }
            results.add(sb.toString());
        });
        return results;
    }
}
